package com.lh.Mybatis.util;

import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.IOException;
import java.io.InputStream;

/**
 * 作者：idea
 * 日期：2018/7/5
 * 描述：
 */
public class SessionFactory {
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;
    private static String MYBATIS_FILE_PATH="MyBatis-conf.xml";

    static {
        InputStream in= null;
        try {
            in = Resources.getResourceAsStream(MYBATIS_FILE_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
    }

    //获取一个模式为批处理类型的session
    public static SqlSession getBatchSession(){
        return sqlSessionFactory.openSession(ExecutorType.BATCH,false);
    }

    public static SqlSession getSqlSession() throws IOException {
        if(sqlSession==null){
            synchronized (SqlSessionFactory.class){
                if(sqlSession==null){
                    sqlSession=sqlSessionFactory.openSession();
                    return sqlSession;
                }else{
                    return sqlSession;
                }
            }
        }else{
            return sqlSession;
        }
    }
}
